import { createRouter,createWebHashHistory } from "vue-router";
import routes from '../router/routes'
import { getToken } from "@/plugins/cookies";
import { storeData } from "@/strore/index"; //pinia
import { useCookies } from "@vueuse/integrations/useCookies"; // 引入cookie
import nprogress from 'nprogress'  //进度条d
import 'nprogress/nprogress.css'

const cookie = useCookies(); // cookie的调用

const router = createRouter({
  history:createWebHashHistory(),
  routes
})

// 判断 新标签在tallist中有么  没有push进去  追加进cookie缓存中
const addTabs = (tabList:any,tab:any) =>{
  // 不加入login菜单
  if(tab.path == '/login'){
    tabList = []
  }else{
    const noTab = tabList.findIndex((t:any)=>t.path == tab.path) == -1
    if(noTab){
      tabList.push(tab)
    }
    cookie.set("tabList",tabList)
  } 
}

// 路由前置守卫
router.beforeEach((to, from, next) => {
  console.log('to==>',to)
  // console.log('from==>',from)

  // 进度条
  nprogress.start()

  // tab活动标签
  const counter = storeData(); // pinia的调用，必须卸载守卫里面，否则报错
  counter.activeTab = to.path
  var thisN = {
    title: to.meta.title,
    path: to.path
  }
  addTabs(counter.tabList,thisN);
  if(counter.tabList.length > 1){
    if(counter?.tabList[0]?.path != '/'){
      var one:any = counter.tabList[0]
      var i = counter.tabList.findIndex(e=>e.path == '/')
      counter.tabList[0] = counter.tabList[i]
      counter.tabList[i] = one
      cookie.remove('tabList')
      cookie.set("tabList",counter.tabList)
    }
  }

  // 面包屑
  counter.breadcrumb = (to.matched) as any

  // token
  const token = getToken()
  if(!token && to.path != '/login' ){
    counter.tabList = []
    ElMessage.warning('用户登录失效，请先登录')
    return next({path: '/login'})
  }
  if(token && to.path == '/login'){
    ElMessage.warning('请勿重复登录')
    return next({path: from.path ? from.path : '/'})
  }
  next()
})

router.afterEach(() => {
  nprogress.done()
})

export default router